package net.zhengxinyun.performance.service.indicators;

import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.entity.CountryIndicatorsEntity;
import net.zhengxinyun.performance.filter.CountryIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryScoreFilter;
import net.zhengxinyun.performance.mapper.Indicators.CountryIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryScoreEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * @Auther: hyp
 * @Date: 2018/10/29 18:11
 */
@Service
public class CountryIndicatorsServiceImpl implements CountryIndicatorsService {

    private CountryIndicatorsEntityMapper countryIndicatorsEntityMapper;

    private CountryScoreEntityMapper countryScoreEntityMapper;

    @Autowired
    public CountryIndicatorsServiceImpl(CountryIndicatorsEntityMapper countryIndicatorsEntityMapper, CountryScoreEntityMapper countryScoreEntityMapper) {
        this.countryIndicatorsEntityMapper = countryIndicatorsEntityMapper;
        this.countryScoreEntityMapper = countryScoreEntityMapper;
    }

    @Override
    @Transactional
    public String delete(CountryIndicatorsEntity countryIndicatorsEntity) {
        int i;
        CountryIndicatorsEntity entity = countryIndicatorsEntityMapper.selectByPrimaryKey(countryIndicatorsEntity.getId());
        if ("一级指标".equals(entity.getIndexType())){
            CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
            countryIndicatorsFilter.setSuperiorIndexId(entity.getId().toString());
            List<CountryIndicatorsFilter> list =  countryIndicatorsEntityMapper.query(countryIndicatorsFilter);
            for (CountryIndicatorsFilter filter:list) {
               i =  countryIndicatorsEntityMapper.deleteByPrimaryKey(filter.getId());
                if (i == 0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return "下属指标删除失败，请联系管理员";
                }
                countryScoreEntityMapper.deleteByIndexId(filter.getId().toString());
            }
        }
        i =  countryIndicatorsEntityMapper.deleteByPrimaryKey(countryIndicatorsEntity.getId());
        if (i == 0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败，请联系管理员";
        }
        return "删除成功";
    }

    @Override
    public int update(CountryIndicatorsEntity countryIndicatorsEntity) {
        return countryIndicatorsEntityMapper.updateByPrimaryKeySelective(countryIndicatorsEntity);
    }

    @Override
    public int insert(CountryIndicatorsEntity countryIndicatorsEntity) {
        return countryIndicatorsEntityMapper.insert(countryIndicatorsEntity);
    }

    @Override
    public List<CountryIndicatorsFilter> query(CountryIndicatorsFilter countryIndicatorsFilter) {
        return countryIndicatorsEntityMapper.query(countryIndicatorsFilter);
    }

    @Override
    public Integer queryForCount(CountryIndicatorsFilter countryIndicatorsFilter) {
        return countryIndicatorsEntityMapper.queryForCount(countryIndicatorsFilter);
    }

    @Override
    public void setIdByName(String name, String dateTime, CountryIndicatorsEntity countryIndicatorsEntity) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("dateTime", dateTime);
        String sysId = countryIndicatorsEntityMapper.getIdByIndexName(map);
        countryIndicatorsEntity.setSuperiorIndexId(sysId);
    }

    /**
     * 分数录入页查询
     *
     * @param countryIndicatorsFilter//?0.
     * @return
     */
    @Override
    public List<CountryIndicatorsFilter> querySecondIndex(CountryIndicatorsFilter countryIndicatorsFilter) {
        if ("4".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit("");
        }
        List<CountryIndicatorsFilter> filterList = countryIndicatorsEntityMapper.queryByTwoTable(countryIndicatorsFilter);
        StringBuffer str = new StringBuffer();
        CountryScoreFilter countryScoreFilter = new CountryScoreFilter();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();
        //在循环中要去除list中的元素用迭代器，否则会报错。
        Iterator<CountryIndicatorsFilter> it = filterList.iterator();
        while (it.hasNext()) {
            CountryIndicatorsFilter filter = it.next();
            if (StringUtils.isBlank(filter.getMainUnit())){
                copyList.add(filter);
                it.remove();
                continue;
            }
        }
        CountryIndicatorsFilter countryIndictorsFilter = new CountryIndicatorsFilter();
        for (CountryIndicatorsFilter c:copyList) {
            countryIndictorsFilter.setSuperiorIndexId(c.getId().toString());
            List<CountryIndicatorsFilter> cList = countryIndicatorsEntityMapper.query(countryIndictorsFilter);
            filterList.addAll(cList);
        }
        for (CountryIndicatorsFilter filter:filterList) {
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                CountryIndicatorsEntity firstIndex = countryIndicatorsEntityMapper.selectByPrimaryKey(Long.parseLong(filter.getSuperiorIndexId()));
                str.setLength(0);
                str.append(firstIndex.getIndexName());
                str.append("(" + firstIndex.getWeight() + ")");
                filter.setSuperiorIndexId(str.toString());
            }
            countryScoreFilter.setIndicatorsId(filter.getId().toString());
        }
        return filterList;
    }

    /**
     * 根据传进来的一级指标返回对应的二级指标的map
     *
     * @param list
     * @return
     */
    public List<Map<String, Object>> getIndexMap(List<CountryIndicatorsFilter> list) {
        List<Map<String, Object>> indexList = new ArrayList<>();
        CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();
        for (CountryIndicatorsFilter filter : list) {
            HashMap indexMap = new HashMap();
            indexMap.put("firstName", filter);
            countryIndicatorsFilter.setIndexType("");
            countryIndicatorsFilter.setSuperiorIndexId(filter.getId().toString());
            List<CountryIndicatorsFilter> secondIndexList = query(countryIndicatorsFilter);
            Iterator<CountryIndicatorsFilter> it = secondIndexList.iterator();
            while (it.hasNext()) {
                CountryIndicatorsFilter c = it.next();
                if (StringUtils.isBlank(c.getLeadUnit())) {
                    copyList.add(c);
                    it.remove();
                }
            }
            for (CountryIndicatorsFilter f:copyList) {
                countryIndicatorsFilter.setSuperiorIndexId(f.getId().toString());
                List<CountryIndicatorsFilter> sonList = query(countryIndicatorsFilter);
                secondIndexList.addAll(sonList);
            }
            indexMap.put("secondIndex", secondIndexList);
            indexList.add(indexMap);
        }
        return indexList;
    }

    /**
     * \
     *
     * @param countryIndicatorsFilter
     * @return
     */
    @Override
    public int queryByTwoTableCount(CountryIndicatorsFilter countryIndicatorsFilter) {
        int i = countryIndicatorsEntityMapper.queryByTwoTableCount(countryIndicatorsFilter);
        return i;
    }

    public int queryForAuditCount(CountryIndicatorsFilter countryIndicatorsFilter) {
        int i = countryIndicatorsEntityMapper.queryForAuditCount(countryIndicatorsFilter);
        return i;
    }

    @Override
    @Transactional
    public String setEndTime(List<CountryIndicatorsEntity> list,String endTime,String warnType) {
        for (CountryIndicatorsEntity countryIndicatorsEntity :list) {
            countryIndicatorsEntity.setEndTime(endTime);
            countryIndicatorsEntity.setWarnType(warnType);
            int i = countryIndicatorsEntityMapper.updateByPrimaryKeySelective(countryIndicatorsEntity);
            if (i == 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "设置失败";
            }
        }
        return "设置成功";
    }

    @Override
    public List<CountryIndicatorsFilter> queryWarn(String today, String dateTime) {
        CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
        countryIndicatorsFilter.setEndTime(today);
        countryIndicatorsFilter.setDateTime(dateTime);
        List<CountryIndicatorsFilter> list = countryIndicatorsEntityMapper.queryWarn(countryIndicatorsFilter);
        return list;
    }

    @Override
    public CountryIndicatorsEntity queryById(Long id) {
        return countryIndicatorsEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<CountryIndicatorsFilter> queryForAudit(CountryIndicatorsFilter countryIndicatorsFilter) {
        if ("4".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit(null);
        }
        //应前端要求，给我状态值5就是搜索全部
        if ("5".equals(countryIndicatorsFilter.getAudit())) {
            countryIndicatorsFilter.setAudit("");
        }
        List<CountryIndicatorsFilter> filterList = countryIndicatorsEntityMapper.queryForAudit(countryIndicatorsFilter);
        StringBuffer str = new StringBuffer();
        List<CountryIndicatorsFilter> copyList = new ArrayList<>();
        CountryScoreFilter countryScoreFilter = new CountryScoreFilter();
        //在循环中要去除list中的元素用迭代器，否则会报错。
        Iterator<CountryIndicatorsFilter> it = filterList.iterator();
        while (it.hasNext()) {
            CountryIndicatorsFilter filter = it.next();
            if (StringUtils.isBlank(filter.getMainUnit())){
                copyList.add(filter);
                it.remove();
                continue;
            }
        }
        CountryIndicatorsFilter countryIndictorsFilter = new CountryIndicatorsFilter();
        for (CountryIndicatorsFilter c:copyList) {
            countryIndictorsFilter.setSuperiorIndexId(c.getId().toString());
            List<CountryIndicatorsFilter> cList = countryIndicatorsEntityMapper.query(countryIndictorsFilter);
            filterList.addAll(cList);
        }
        for (CountryIndicatorsFilter filter:filterList) {
            if (StringUtils.isNotBlank(filter.getSuperiorIndexId())) {
                CountryIndicatorsEntity firstIndex = countryIndicatorsEntityMapper.selectByPrimaryKey(Long.parseLong(filter.getSuperiorIndexId()));
                str.setLength(0);
                str.append(firstIndex.getIndexName());
                str.append("(" + firstIndex.getWeight() + ")");
                filter.setSuperiorIndexId(str.toString());
            }
            countryScoreFilter.setIndicatorsId(filter.getId().toString());
        }
        return filterList;
    }


}
